package com.orange.cetback.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.orange.cetback.common.enums.MaterialType;
import com.orange.cetback.common.enums.MaterialTypeScore;
import com.orange.cetback.common.vo.PageResult;
import com.orange.cetback.pojo.dto.ExamPapersDTO;
import com.orange.cetback.pojo.dto.PaperDTO;
import com.orange.cetback.pojo.entity.ExamPapers;
import com.orange.cetback.mapper.ExamPapersMapper;
import com.orange.cetback.pojo.entity.Materials;
import com.orange.cetback.pojo.entity.QuestionOptions;
import com.orange.cetback.pojo.entity.Questions;
import com.orange.cetback.service.ExamPapersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.orange.cetback.service.MaterialsService;
import com.orange.cetback.service.QuestionOptionsService;
import com.orange.cetback.service.QuestionsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenenjun
 * @since 2025-02-16
 */
@Slf4j
@Service
public class ExamPapersServiceImpl extends ServiceImpl<ExamPapersMapper, ExamPapers> implements ExamPapersService {
    @Autowired
    private MaterialsService materialsService;
    @Autowired
    private QuestionsService questionsService;
    @Autowired
    private QuestionOptionsService questionOptionsService;

    @Override
    public List<ExamPapers> list(ExamPapersDTO examPapersDTO) {
        LambdaQueryWrapper<ExamPapers> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ExamPapers::getStudyLevel, examPapersDTO.getStudyLevel());
        List<ExamPapers> examPapers = this.baseMapper.selectList(wrapper);
        return examPapers;
    }

    @Override
    public PageResult<ExamPapers> pageQuery(PaperDTO paperDTO) {
        Page<ExamPapers> page = new Page<>(paperDTO.getPageNum(), paperDTO.getPageSize());
        LambdaQueryWrapper<ExamPapers> wrapper = new LambdaQueryWrapper<>();
        if (!paperDTO.getPaperClass().equals("")) {
            wrapper.eq(ExamPapers::getPaperClass, paperDTO.getPaperClass());
        }
        if (!paperDTO.getStudyLevel().equals("")) {
            wrapper.eq(ExamPapers::getStudyLevel, paperDTO.getStudyLevel());
        }
        wrapper.like(ExamPapers::getPaperTitle, paperDTO.getPaperTitle());
        wrapper.orderByDesc(ExamPapers::getCreateTime);
        this.baseMapper.selectPage(page, wrapper);
        return new PageResult<>(page.getTotal(), page.getRecords());
    }

    @Transactional
    @Override
    public void uploadPaperQuestion(Integer paperId, MultipartFile file) {
        StringBuilder vocabulary = new StringBuilder();
        StringBuilder writing = new StringBuilder();
        StringBuilder longReading = new StringBuilder();
        StringBuilder carefulReading = new StringBuilder();
        StringBuilder translation = new StringBuilder();
        //根据每个part 的文本内容进行匹配，然后进行替换
        Pattern PART_PATTERN = Pattern.compile("^Part ([IVX]+)\\s+(.+?)\\s+\\((.+?)\\)$");
        Pattern SECTION_PATTERN = Pattern.compile("^Section ([A-Z])$");
        try (XWPFDocument document = new XWPFDocument(file.getInputStream())) {
            // 读取段落
            String partNumber = null;
            String sectionNumber = null;
            boolean writingFlag = false;
            boolean vocabularyFlag = false;
            boolean longReadingFlag = false;
            boolean carefulReadingFlag = false;
            boolean translationFlag = false;
            for (XWPFParagraph p : document.getParagraphs()) {
                String text = p.getText().trim();
                Matcher partMatcher = PART_PATTERN.matcher(text);

                if (partMatcher.find()) {
                    partNumber = partMatcher.group(1);
                    sectionNumber = null;
                }

                // 解析Section
                Matcher sectionMatcher = SECTION_PATTERN.matcher(text);

                if (sectionMatcher.find()) {
                    sectionNumber = sectionMatcher.group(1);
                }

                //获取词汇理解
                if (sectionNumber != null && partNumber != null && partNumber.equals("III") && sectionNumber.equals("A") && !text.startsWith("Directions") && !text.startsWith("Section A")) {
                    vocabularyFlag = true;
                }else {
                    vocabularyFlag = false;
                }

                if (vocabularyFlag && !text.equals("")){
                    vocabulary.append(text).append("\n");
                }

                //获取写作
                if (partNumber != null && partNumber.equals("I") && !text.startsWith("Part")) {
                    writingFlag = true;
                }else {
                    writingFlag = false;
                }

                if (writingFlag && !text.equals("")){
                    writing.append(text).append("\n");
                }
                //获取长篇阅读
                if (sectionNumber != null && partNumber != null && partNumber.equals("III") && sectionNumber.equals("B") && !text.startsWith("Directions") && !text.startsWith("Section B")) {
                    longReadingFlag = true;
                }else {
                    longReadingFlag = false;
                }

                if (longReadingFlag && !text.equals("")){
                    longReading.append(text).append("\n");
                }
                //获取仔细阅读
                if (sectionNumber != null && partNumber != null && partNumber.equals("III") && sectionNumber.equals("C") && !text.startsWith("Directions") && !text.startsWith("Section C")) {
                    carefulReadingFlag = true;
                }else {
                    carefulReadingFlag = false;
                }

                if (carefulReadingFlag && !text.equals("")){
                    carefulReading.append(text).append("\n");
                }

                //获取翻译
                if (partNumber != null && partNumber.equals("IV") && !text.startsWith("Part") && !text.startsWith("Directions")) {
                    translationFlag = true;
                }else {
                    translationFlag = false;
                }

                if (translationFlag && !text.equals("")){
                    translation.append(text).append("\n");
                }

            }

        }catch (IOException e){
            throw new RuntimeException(e);
        }
        //保存writing
        Materials writingMaterials = Materials.builder()
                .paperId(paperId)
                .materialType(MaterialType.WRITING.name())
                .content(writing.toString().split("参考范文\n")[0])
                .build();
        materialsService.save(writingMaterials);
        Questions writingQuestion = Questions.builder()
                .materialId(writingMaterials.getMaterialId())
                .content("writing")
                .baseScore(new BigDecimal(String.valueOf(MaterialTypeScore.TRANSLATION.getScore())))
                .answer(writing.toString().split("参考范文\n")[1])
                .build();
        questionsService.save(writingQuestion);
        //保存vocabulary
        Materials vocabularyMaterials = Materials.builder()
                .paperId(paperId)
                .materialType(MaterialType.VOCABULARY.name())
                .content(vocabulary.toString().split("解析\n")[0])
                .build();
        materialsService.save(vocabularyMaterials);
        List<Questions> vocabularyQuestions = parseVocabularyQuestions(vocabulary.toString(), vocabularyMaterials.getMaterialId());
        questionsService.saveBatch(vocabularyQuestions);
        List<QuestionOptions> vocabularyQuestionOptions = parseVocabularyQuestionsOptions(file, vocabularyMaterials.getMaterialId());
        questionOptionsService.saveBatch(vocabularyQuestionOptions);
        //解析长篇阅读
        Materials longReadingMaterials = Materials.builder()
                .paperId(paperId)
                .materialType(MaterialType.LONG_READING.name())
                .content(longReading.toString().split("\n")[0])
                .build();
        materialsService.save(longReadingMaterials);
        List<Questions> LongReadingQuestions = parseLongReadingQuestions(longReading.toString(), longReadingMaterials.getMaterialId());
        questionsService.saveBatch(LongReadingQuestions);
        List<QuestionOptions> longReadingQuestionOptions = parseLongReadingQuestionOptions(longReading.toString(), longReadingMaterials.getMaterialId());
        questionOptionsService.saveBatch(longReadingQuestionOptions);
        //解析仔细阅读
        Materials carefulReadingMaterialsOne = parseMaterials(carefulReading.toString().split("(?=Passage [A-Za-z]+\\nQuestions)")[0], paperId);
        materialsService.save(carefulReadingMaterialsOne);
        List<Questions> questionsListOne = parseCarefulReadingQuestions(carefulReading.toString().split("(?=Passage [A-Za-z]+\\nQuestions)")[0], carefulReadingMaterialsOne.getMaterialId());
        questionsService.saveQuestions(questionsListOne);
        Materials carefulReadingMaterialsTwo = parseMaterials(carefulReading.toString().split("(?=Passage [A-Za-z]+\\nQuestions)")[1], paperId);
        materialsService.save(carefulReadingMaterialsTwo);
        List<Questions> questionsListTwo = parseCarefulReadingQuestions(carefulReading.toString().split("(?=Passage [A-Za-z]+\\nQuestions)")[1], carefulReadingMaterialsTwo.getMaterialId());
        questionsService.saveQuestions(questionsListTwo);
        Materials translationMaterials = Materials.builder()
                .paperId(paperId)
                .materialType(MaterialType.TRANSLATION.name())
                .content(translation.toString().split("参考译文\n")[0])
                .build();
        materialsService.save(translationMaterials);
        Questions translationQuestion = Questions.builder()
                .materialId(translationMaterials.getMaterialId())
                .content("translation")
                .baseScore(new BigDecimal(String.valueOf(MaterialTypeScore.TRANSLATION.getScore())))
                .answer(translation.toString().split("参考译文\n")[1])
                .build();
        questionsService.save(translationQuestion);
    }

    /**
     * 解析词汇理解
     * @param content
     * @return
     */
    private List<Questions> parseVocabularyQuestions(String content, Integer materialId){
        String[] split = content.split("解析\n");
        String analysis = split[1];
        List<Questions> questions = new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder();
        Pattern pattern = Pattern.compile("^\\d+\\.\\s.+");
        Questions question = null;
        for (String line : analysis.split("\n")) {
            if (pattern.matcher(line).matches()){
                if (question != null)
                    questions.add(question);
                question = new Questions();
                question.setAnswer(line.split("\\.\\s")[1]);
                question.setMaterialId(materialId);
                question.setBaseScore(new BigDecimal(String.valueOf(MaterialTypeScore.LONG_READING.getScore())));
                stringBuilder = new StringBuilder();
            }else {
                stringBuilder.append(line).append("\n");
                question.setAnalysis(stringBuilder.toString());
            }
        }
        questions.add(question);
        for (int i = 0; i < questions.size(); i++){
            questions.get(i).setContent("【" + (i + 26) + "】");
        }
        return questions;
    }
    /**
     * 解析词汇理解选项
     * @param file
     * @return
     */
    private List<QuestionOptions> parseVocabularyQuestionsOptions(MultipartFile file, Integer materialId) {
        List<QuestionOptions> questionOptions = new ArrayList<>();
        try {
            XWPFDocument doc = new XWPFDocument(file.getInputStream());
            // 读取表格
            for (XWPFTable table : doc.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        if (!cell.getText().equals("")){
                            QuestionOptions questionOption = QuestionOptions.builder()
                                    .materialId(materialId)
                                    .optionLabel(cell.getText().split("\\)\\s+")[0])
                                    .optionContent(cell.getText().split("\\)\\s+")[1])
                                    .build();
                            questionOptions.add(questionOption);
                        }
                    }
                }
            }
            questionOptions.sort(Comparator.comparing(QuestionOptions::getOptionLabel));
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
        return questionOptions;
    }
    /**
     * 解析长篇阅读问题
     * @param content
     * @return
     */
    private List<Questions> parseLongReadingQuestions(String content, Integer materialId){
        String[] split = content.split("解析\n");
        List<String> questionList = extractQuestions(split[0]);
        String analysis = split[1];
        List<Questions> questions = new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder();
        Pattern pattern = Pattern.compile("^\\d+\\.\\s.+");
        Questions question = null;
        for (String line : analysis.split("\n")) {
            if (pattern.matcher(line).matches()){
                if (question != null)
                    questions.add(question);
                question = new Questions();
                question.setAnswer(line.split("\\.\\s")[1]);
                question.setBaseScore(new BigDecimal(String.valueOf(MaterialTypeScore.LONG_READING.getScore())));
                question.setMaterialId(materialId);
                stringBuilder = new StringBuilder();
            }else {
                stringBuilder.append(line).append("\n");
                question.setAnalysis(stringBuilder.toString());
            }
        }
        questions.add(question);
        for (int i = 0; i < questions.size(); i++){
            questions.get(i).setContent(questionList.get(i));
        }
        return questions;
    }
    private List<String> extractQuestions(String content) {
        List<String> questions = new ArrayList<>();
        // 匹配 "数字. 开头" 的问题格式
        Pattern pattern = Pattern.compile("^\\d+\\.\\s.+");

        Arrays.stream(content.split("\n"))
                .filter(line -> pattern.matcher(line).matches())
                .forEach(questions::add);

        return questions;
    }
    /**
     * 解析长篇阅读选项
     * @param content
     * @return
     */
    private List<QuestionOptions> parseLongReadingQuestionOptions(String content, Integer materialId) {
        // 第一阶段：分离主内容和问题部分
        String[] parts = content.split("(?=\\d{1,2}\\.\\s)");
        content = parts.length > 0 ? parts[0] : content;
        List<QuestionOptions> questionOptions = new ArrayList<>();
        Pattern pattern = Pattern.compile("(?m)^([A-L])\\)(.*?)(?=^[A-L]\\)|\\Z)", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            String label = matcher.group(1);
            String optionContent = matcher.group(2).trim()
                    .replaceAll("\\n+", " ")  // 合并换行为空格
                    .replaceAll("\\s+", " "); // 合并多个空格
            questionOptions.add(QuestionOptions.builder()
                    .materialId(materialId)
                    .optionLabel(label)
                    .optionContent(optionContent)
                    .build());
        }
        return questionOptions;
    }
    /**
     * 解析仔细阅读材料
     * @param passage
     * @return
     */
    private Materials parseMaterials(String passage, Integer paperId) {
        // 分离内容和问题解析
        String[] parts = passage.split("(?=\\d{1,2}\\.\\s)");
        String content = parts.length > 0 ? parts[0] : passage;
        Materials materials = Materials.builder()
                .paperId(paperId)
                .content(content)
                .materialType(MaterialType.CAREFUL_READING.name())
                .build();

        return materials;
    }

    /**
     * 解析获取仔细阅读问题
     * @param passage
     * @param materialId
     * @return
     */
    private List<Questions> parseCarefulReadingQuestions(String passage, Integer materialId) {
        List<Questions> questions = new ArrayList<>();
        // 分割题目块
        String[] questionBlocks = passage.split("(?=\\d{2}\\.\\s)");
        // 解析所有问题
        Pattern pattern = Pattern.compile(
                "(\\d{2})\\.\\s(.+?)\\n" +      // 题号和题干
                        "((?:[A-D]\\).+?\\n)+)",
                Pattern.DOTALL);
        for (String block : questionBlocks) {
            Matcher matcher = pattern.matcher(block);
            if (matcher.find()) {
                // 1. 先创建问题主体
                Questions question = Questions.builder()
                        .materialId(materialId)
                        .content(matcher.group(2).trim())
                        .answer(parseAnswer(passage.split("解析\n")[1], matcher.group(1))) // 从解析文本提取答案
                        .analysis(parseAnalysis(passage.split("解析\n")[1], matcher.group(1)))
                        .baseScore(new BigDecimal(String.valueOf(MaterialTypeScore.CAREFUL_READING.getScore())))
                        .build();

                // 2. 解析选项并关联questionId（需后续设置）
                List<QuestionOptions> options = parseOptions(matcher.group(3));
                question.setOptions(options);

                questions.add(question);
            }
        }
        return questions;
    }
    // 解析选项并暂存（此时questionId未确定）
    private List<QuestionOptions> parseOptions(String optionsText) {
        return Pattern.compile("([A-D])\\)\\s*((?:(?!\\s+[A-D]\\)).)+)")
                .matcher(optionsText.replace("\t", " "))
                .results()
                .map(match -> QuestionOptions.builder()
                        .optionLabel(match.group(1))
                        .optionContent(match.group(2).trim().replaceAll("\\s+", " "))
                        .build())
                // 新增排序逻辑
                .sorted(Comparator.comparingInt(opt ->
                        "ABCD".indexOf(opt.getOptionLabel())
                ))
                .collect(Collectors.toList());
    }


    // 答案解析方法示例（支持多种格式）
    private String parseAnswer(String analysisText, String questionNumber) {
        List<String> questions = extractQuestions(analysisText);
        for (String question : questions) {
            if (question.startsWith(questionNumber)) {
                return question.split("\\.\\s")[1];
            }
        }
        return "";
    }
    // 解析解析
    private String parseAnalysis(String analysisText, String questionNumber) {
        StringBuilder stringBuilder = new StringBuilder();
        Pattern pattern = Pattern.compile("(\\d{2})\\.\\s(.+)");
        boolean flag = false;
        for (String line : analysisText.split("\n")) {
            Matcher matcher = pattern.matcher(line);
            if (matcher.find()){
                flag = matcher.group(1).equals(questionNumber);
            }
            if (flag && !line.startsWith(questionNumber)){
                stringBuilder.append(line).append("\n");
            }
        }
        return stringBuilder.toString();

    }

}
